package zuosheng.Binarytree;

import java.util.Stack;

/**
 * @author lj
 * @Description: 非递归遍历
 * @date 2020-11-14 19:50
 * @QQ 851477108
 */


public class feidiguibianli {
    public static class Node{
        public int value;
        public Node left;
        public Node right;
        public Node(int data){
            this.value = data;
        }
    }

    //前序遍历
    public void preOrderUnRecur(Node head){
        System.out.println("pre-order: ");
        if (head!=null){
            Stack<Node> stack = new Stack<>();
            stack.add(head);
            while (!stack.isEmpty()){
                head = stack.pop();
                System.out.println(head.value + " ");
                if (head.right != null){
                    stack.push(head.right);
                }
                if (head.left != null){
                    stack.push(head.left);
                }
            }
        }
        System.out.println();
    }

    //中序遍历
    public void inOrderUnRecur(Node head){
        System.out.println("in-order: ");
        if (head != null){
            Stack<Node> stack = new Stack<>();
            while (!stack.isEmpty() || head != null){
                if (head != null){
                    stack.push(head);
                    head = head.left;
                }else {
                    head = stack.pop();
                    System.out.print(head.value + " ");
                    head = head.right;
                }
            }
        }
        System.out.println();
    }

    //后序遍历-双栈方法
    public void posOrderUnRecur(Node head){
        System.out.println("pos-order: ");
        if (head != null){
            Stack<Node> stack1 = new Stack<>();
            Stack<Node> stack2 = new Stack<>();
            stack1.push(head);
            while (!stack1.isEmpty()){
                head = stack1.pop();
                stack2.push(head);
                if (head.left != null){
                    stack1.push(head.left);
                }
                if (head.right != null){
                    stack2.push(head.right);
                }
            }
            while (!stack2.isEmpty()){
                System.out.println(stack2.pop().value + " ");
            }
        }
        System.out.println();
    }
}
